package ru.spbu.math.android.cbrf.charts;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import ru.spbu.math.android.cbrf.R;

import java.util.Calendar;
import java.util.GregorianCalendar;


/**
 * @author  Nikita
 */
public class DateDialog extends Dialog {

    private AlertDialog invalidDateAlert;
    private Calendar start;
	private Calendar end;
    /**
	 * @uml.property  name="chartActivity"
	 * @uml.associationEnd  
	 */
    private  ChartsActivity chartActivity;

    
    public DateDialog(Context context, ChartsActivity ca) {
        super(context);
        setContentView(R.layout.date_dialog);
        setTitle(getContext().getResources().getString(R.string.DateDialog));
        final DatePicker startDatePicker = (DatePicker) findViewById(R.id.DatePickerStart);
        final DatePicker endDatePicker = (DatePicker) findViewById(R.id.DatePickerEnd);
        Button applyButton = (Button) findViewById(R.id.ApplyButton);

        chartActivity = ca;

        start = chartActivity.getStartDate();
        end = chartActivity.getEndDate();

        startDatePicker.updateDate(start.get(Calendar.YEAR), start.get(Calendar.MONTH), start.get(Calendar.DAY_OF_MONTH));
        endDatePicker.updateDate(end.get(Calendar.YEAR), end.get(Calendar.MONTH), end.get(Calendar.DAY_OF_MONTH));

        AlertDialog.Builder InvalidDataBilder = new AlertDialog.Builder(this.getContext());
        InvalidDataBilder.setMessage("Invalid date range");
        InvalidDataBilder.setCancelable(false);
        InvalidDataBilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                invalidDateAlert.dismiss();
            }
        });

        invalidDateAlert = InvalidDataBilder.create();


        applyButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

                start = new GregorianCalendar(startDatePicker.getYear(), startDatePicker.getMonth(), startDatePicker.getDayOfMonth());
                end = new GregorianCalendar(endDatePicker.getYear(), endDatePicker.getMonth(), endDatePicker.getDayOfMonth());
                if (end.compareTo(start) > 0) {
                    chartActivity.setDateRange(start, end);
                    DateDialog.this.hide();
                } else invalidDateAlert.show();
                
            }
        });
    }
}
